﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace KouDai.Phone.Controls
{
    public class ScrollableLongListSelector : ListBox
    {
        #region Fields
        private ScrollViewer _sv;
        #endregion

        #region ApplyTemplate

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _sv = FindFirstChildOfType<ScrollViewer>(this);
            if (_sv == null)
            {
                throw new ArgumentNullException("ScrollViewer is null");
            }
            this.SetBinding(ScrollViewer.VerticalOffsetProperty, new Binding { Source = _sv, Path = new PropertyPath("VerticalOffset") });
        }

        #endregion

        #region DependencyProperty

        private static readonly DependencyProperty VerticalOffsetShadowProperty =
            DependencyProperty.Register("VerticalOffsetShadow", typeof(double), typeof(ScrollableLongListSelector), new PropertyMetadata(-1.0, new PropertyChangedCallback(OnVerticalOffsetShadowChanged)));


        private static void OnVerticalOffsetShadowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

        }

        #endregion

        #region UtilMethod

        private static T FindFirstChildOfType<T>(DependencyObject root) where T : class
        {
            // Enqueue root node
            var queue = new Queue<DependencyObject>();
            queue.Enqueue(root);
            while (0 < queue.Count)
            {
                // Dequeue next node and check its children
                var current = queue.Dequeue();
                for (var i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
                {
                    var child = VisualTreeHelper.GetChild(current, i);
                    var typedChild = child as T;
                    if (null != typedChild)
                    {
                        return typedChild;
                    }
                    // Enqueue child
                    queue.Enqueue(child);
                }
            }
            // No children match
            return null;
        }

        #endregion
      
    }
}
